package com.action;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/**
 * Servlet implementation class UpFileAction
 */
public class UpFileAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UpFileAction() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// response.getWriter().append("Served at:
		// ").append(request.getContextPath());
		// 可以用request.getPart()方法获得名为photo的上传附件
		// 也可以用request.getParts()获得所有上传附件（多文件上传）
		// 然后通过循环分别处理每一个上传的文件
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// doGet(request, response);
		// 可以用request.getPart()方法获得名为photo的上传附件
		// 也可以用request.getParts()获得所有上传附件（多文件上传）
		// 然后通过循环分别处理每一个上传的文件
		Part p = request.getPart("photo");
		if (p != null && p.getSubmittedFileName().length() > 0) {
			// 服务端保存文件的路径
			String path = request.getServletContext().getRealPath("/upload");
			System.out.println("文件保存路径：" + path);
			// Servlet 3.1规范中可以用Part对象的getSubmittedFileName()方法获得上传的文件名
			// 更好的做法是为上传的文件进行重命名（避免同名文件的相互覆盖）
			p.write(path + "/" + p.getSubmittedFileName());
			request.setAttribute("hint", "Upload Successfully!");
		} else {
			request.setAttribute("hint", "Upload failed!");
		}

		// 跳转回到上传页面
		request.getRequestDispatcher("upload").forward(request, response);

	}

}
